package dao

import (
	"context"
	"errors"
	"fmt"
	"github.com/sashabaranov/go-openai"
	"hospital-srv/basic/inits"
	__ "hospital-srv/basic/proto"
	"hospital-srv/handler/models"
	"log"
	"strconv"
)

// ai提问与回复
func HandleAiResp(question string) (string, error) {
	// 2. 构造请求（与 OpenAI 格式一致）
	req := openai.ChatCompletionRequest{
		Model: inits.Config.Model, // DeepSeek 聊天模型
		Messages: []openai.ChatCompletionMessage{
			{
				Role:    openai.ChatMessageRoleUser,
				Content: question,
			},
		},
	}
	// 3. 发送请求
	resp, err := inits.DP.CreateChatCompletion(context.Background(), req)
	if err != nil {
		log.Println("请求失败: ", err)
		return "", err
	}
	content := resp.Choices[0].Message.Content
	// 购物车添加

	return content, nil
}

// 保存提问历史
func SetQuestion(userId, roomId int64, question string, answer string) error {

	var reply string
	reply = fmt.Sprintf("%v", answer)
	p := models.Problem{
		UserId:  uint32(userId),
		RoomId:  int32(roomId),
		Problem: question,
		Reply:   reply,
	}

	if err := p.CreateProblem(); err != nil {
		return errors.New("记录历史失败")
	}
	key := fmt.Sprintf("DeepSeek:%d:%d:%d", userId, roomId, p.Id)
	goodMap := map[string]interface{}{
		"id":          p.Id,
		"userId":      userId,
		"roomId":      roomId,
		"question":    question,
		"content":     answer,
		"create_time": p.CreatedAt,
	}
	err := inits.InitRedis(3).HMSet(context.Background(), key, goodMap).Err()
	if err != nil {
		return errors.New("redis记录历史失败" + err.Error())
	}
	return nil
}

// 提问历史
func QuestionList(userId, roomId int64) (problemList []*__.QuestionList, err error) {

	key := fmt.Sprintf("DeepSeek:%d:%d:*", userId, roomId)
	keys := inits.InitRedis(3).Keys(context.Background(), key).Val()
	if keys != nil {
		for _, v := range keys {
			questionData := inits.InitRedis(3).HGetAll(context.Background(), v).Val()

			id, _ := strconv.Atoi(questionData["id"])
			question := questionData["question"]
			content := questionData["content"]
			problemList = append(problemList, &__.QuestionList{
				Id:      int64(id),
				UserId:  userId,
				Problem: question,
				RoomId:  roomId,
				Reply:   content,
			})
		}
	} else {
		var p models.Problem
		p.UserId = uint32(userId)
		problem, err := p.QuestionHistory()
		if err != nil {
			return nil, errors.New("查询失败：" + err.Error())
		}
		for _, v := range problem {
			list := __.QuestionList{
				Id:      int64(v.Id),
				UserId:  int64(v.UserId),
				Problem: v.Problem,
				RoomId:  int64(v.RoomId),
				Reply:   v.Reply,
			}
			problemList = append(problemList, &list)
		}
	}
	return problemList, err
}
